package com.example.mq.mqserver.datacenter;

import com.example.mq.common.MqException;
import com.example.mq.mqserver.core.Binding;
import com.example.mq.mqserver.core.Exchange;
import com.example.mq.mqserver.core.MSGQueue;
import com.example.mq.mqserver.core.Message;

import java.io.IOException;
import java.util.LinkedList;
import java.util.List;

/*
 * 使用这个类，管理硬盘上所有数据:
 * 1、数据库：交换机、队列、绑定
 * 2、数据文件：消息
 * 上层逻辑需要硬盘操作，统一使用这个类（上层逻辑不关心数据从硬盘上来还是内存中来
 * ）*/
public class DiskDataCenter {
    private DatabaseManager databaseManager = new DatabaseManager();
    private MessageFileManager messageFileManager = new MessageFileManager();

    public void init() {
        //针对两个实例进行初始化
        databaseManager.init();

        //当前init方法是空的，支持后续扩展
        messageFileManager.init();
    }

    //插入交换机
    public void insertExchange(Exchange exchange) {
        databaseManager.insertExchange(exchange);
    }

    //删除交换机
    public void deleteExchange(String exchangeName) {
        databaseManager.deleteExchange(exchangeName);
    }

    //获取所有交换机
    public List<Exchange> getAllExchanges() {
        return databaseManager.selectAllExchange();
    }

    //封装队列操作
    public void insertQueue(MSGQueue queue) throws IOException {
        databaseManager.insertQueue((MSGQueue) queue);
        messageFileManager.createQueueFile(queue.getName());
    }

    public void deleteQueue(MSGQueue queue) {
        databaseManager.deleteQueue((MSGQueue) queue);
    }
    public void deleteQueue(String queueName) {
        databaseManager.deleteQueue(queueName);
    }

    public List<MSGQueue> getAllQueues() {
        return databaseManager.selectAllQueue();
    }

    // 封装绑定操作
    public void insertBinding(Binding binding) {
        databaseManager.insertBinding(binding);
    }

    public void deleteBinding(Binding binding) {
        databaseManager.deleteBinding(binding);
    }

    public List<Binding> selectAllBindings() {
        return databaseManager.selectAllBinding();
    }

    //封装消息
    public void sendMessage(MSGQueue queue, Message message) throws IOException, MqException {
        messageFileManager.sendMessage(queue, message);
    }

    //删除完一个消息后，需要考虑是否gc，因为无效消息增加了
    public void deleteMessage(MSGQueue queue, Message message) throws IOException, MqException, ClassNotFoundException {
        messageFileManager.deleteMessage(queue, message);
        if (messageFileManager.checkGC(queue.getName())) {
            messageFileManager.gc(queue);
        }
    }

    public LinkedList<Message> loadAllMessageFormQueue(MSGQueue queue) throws IOException, MqException, ClassNotFoundException {
        LinkedList<Message> messages = new LinkedList<>();
        messages = messageFileManager.loadAllMessageForQueue(queue.getName());
        return messages;
    }


}
